import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from "../components/public/Home.vue";
import Login from "../views/Login";
import store from "@/store";
import AdminInfo from "../views/AdminInfo.vue";
import {initMenu} from "@/utils/menus";
import FriendChat from "@/views/chat/FriendChat.vue"

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name:Login,
    component:Login,
    hidden:true,
  },
  {
    path:'/home',
    name:'home',
    component:Home,
    children:[
      {
        path: '/chat',
        name:'在线聊天',
        component:FriendChat,
      },
      {
        path: '/userinfo',
        name:'个人中心',
        component:AdminInfo,
      },
    ]
  },
]
const router = new VueRouter({
      routes
})
// router.beforeEach((to, from, next)=> {
//   if (to.path == '/') {
//     next();
//     return;
//   }
//   var name = store.state.user.name;
//   if (name == '未登录') {
//     next({path: '/', query: {redirect: to.path}})
//   } else {
//     initMenu(router, store);
//     next();
//   }
// }
// )
router.beforeEach((to,from,next)=>{
  if (window.sessionStorage.getItem('tokenStr')) {
    // 已经登录
    initMenu(router,store);
    //判断用户是否存在
    if(!window.sessionStorage.getItem('user')){
      return getRequest('/admin/info').then(resp=>{
        if(resp){
          //存入用户信息
          console.log('存入信息');
          window.sessionStorage.setItem('user',JSON.stringify(resp));
          store.commit('init_admin',resp);
          next();
        }
      })
    }
    next();
  }else {
    //未登录  这里是 logout 之后 未登录，去 / 要放行
    if (to.path == '/') {
        next();
    }else if(to.path == '/staffroster'){
      next(to.path);
    }
    else {
      next('/?redirect='+to.path);
    }
  }
})
export default router

